from sqlalchemy import Column, Integer, String, DateTime, Text
from database import Base
from sqlalchemy.sql import func


class RequestLog(Base):
    __tablename__ = "request_logs"
    __table_args__ = {'comment': '日志表'}

    id = Column(Integer, primary_key=True, index=True, comment="主键ID")
    user_id = Column(Integer, index=True, nullable=True, comment="用户ID（匿名请求为 NULL）")
    username = Column(String(32), nullable=True, comment="用户名（匿名请求为 NULL）")

    method = Column(String(10), nullable=False, comment="请求方法 GET/POST 等")
    url = Column(String(255), nullable=False, comment="请求 URL")
    status_code = Column(Integer, nullable=False, comment="响应状态码")
    client_ip = Column(String(50), nullable=False, comment="客户端 IP")
    user_agent = Column(String(255), nullable=True, comment="User-Agent 请求头")
    response_body = Column(Text, nullable=True, comment="响应体内容（部分/截断）")
    request_body = Column(Text, nullable=True, comment="请求体内容")
    request_time = Column(DateTime, nullable=False, default=func.now(), comment="请求时间")

    def __repr__(self):
        return f"<RequestLog {self.method} {self.url} {self.status_code} @ {self.client_ip}>"
